package com.extract.task.o;

import com.eksframework.commons.core.base.EksDate;
import com.extract.es.document.OrderDocument;
import com.extract.es.repository.OrderRepository;
import com.extract.query.ExtractQuery;
import com.extract.query.QueryParameter;
import com.extract.sys.entity.TaskRecord;
import com.extract.task.basic.AbstractTask;
import com.extract.task.basic.TaskResult;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-10-14 17:17
 */
@Slf4j
@Service("O001")
public class O001Task extends AbstractTask {

    @Autowired
    OrderRepository orderRepository;

    /**
     * 执行任务抽象方法
     *
     * @param taskRecord 任务记录
     */
    @Override
    public TaskResult executeTask(TaskRecord taskRecord) {
        log.info("执行任务：{}", taskRecord);
        ExtractQuery extractQuery = ExtractQuery.builder()
                .tenantId(taskRecord.getTenantId())
                .cinemaCode(taskRecord.getCinemaCode())
                .systemCode(taskRecord.getSystemCode())
                .id("com.extract.task.mapper.O001Mapper.findSaleBillList")
                .parameterObject(QueryParameter.of(taskRecord).getParameterMap())
                .build();
        List<Map<String, String>> dataList = super.databaseBuilder.queryData(extractQuery);
        log.info("查询数据记录：{}", dataList.size());
        if(dataList.isEmpty()){
            return TaskResult.builder()
                    .code(TaskResult.SUCCESS_CODE)
                    .lastSign(taskRecord.getLastSign())
                    .build();
        }
        List<OrderDocument> orderDocumentList = Lists.newArrayList();
        dataList.forEach(obj -> orderDocumentList.add(toDocument(obj)));
        orderRepository.saveAll(orderDocumentList);
        return TaskResult.builder()
                .code(TaskResult.SUCCESS_CODE)
                .handlerNum(dataList.size())
                .lastSign(dataList.get(dataList.size() - 1).get("BILL_ID"))
                .build();
    }

    private OrderDocument toDocument(Map<String, String> stringMap){
        return OrderDocument.builder()
                .orderId(stringMap.get("CINEMA_CODE") + stringMap.get("BILL_CODE"))
                .orderCinema(stringMap.get("CINEMA_NAME"))
                .orderDay(EksDate.of(stringMap.get("PAYED_TIME")).toDateString())
                .orderPrice(Double.parseDouble(stringMap.get("PAY_PRICE")))
                .orderTime(EksDate.of(stringMap.get("PAYED_TIME")).toDate())
                .build();
    }
}
